<template>
  <div class="settings-container">
    <h3 class="settings-title">账号安全</h3>
    <div class="settings-item">
      <div class="item-info">
        <div class="item-title">
          <mail-outlined />
          <span>邮箱绑定</span>
        </div>
        <div class="item-desc">
          {{ userstore?.email ? maskEmail(userstore.email) : '未绑定邮箱' }}
        </div>
      </div>
      <a-button 
        type="primary" 
        @click="showEmailModal"
        :disabled="!!userstore?.email"
      >
        {{ userstore?.email ? '已绑定' : '立即绑定' }}
      </a-button>
    </div>

    <!-- 邮箱绑定弹窗 -->
    <a-modal
      v-model:visible="emailModalVisible"
      title="绑定邮箱"
      @ok="handleEmailBind"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="emailForm"
        :rules="emailRules"
        ref="emailFormRef"
        layout="vertical"
      >
        <a-form-item label="邮箱地址" name="email">
          <a-input 
            v-model:value="emailForm.email" 
            placeholder="请输入邮箱地址"
            :disabled="showVerifyCode"
          >
            <template #suffix>
              <a-button 
                type="link" 
                size="small"
                :loading="sendingCode"
                :disabled="showVerifyCode || countdown > 0 || sendingCode"
                @click="debouncedSendCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : (sendingCode ? '发送中...' : '获取验证码') }}
              </a-button>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item label="验证码" name="code" v-if="showVerifyCode">
          <a-input 
            v-model:value="emailForm.code" 
            placeholder="请输入验证码"
          />
        </a-form-item>
      </a-form>

      <template #footer>
        <a-button key="back" @click="() => {emailModalVisible = false}">关闭</a-button>
        <a-button 
            key="submit"
            type="primary" 
            :disabled="!emailForm.email || !emailForm.code"
            :loading="confirmLoading" 
            @click="handleEmailBind"
        >
            绑定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue';
import { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { message } from 'ant-design-vue';
import { MailOutlined } from '@ant-design/icons-vue';

import { sendEmailCaptcha, bindEmail } from '@/api/front/user';
import { debounce } from 'lodash-es';
import useUserStore from '@/store/modules/user';

const emit = defineEmits(['refresh']);
const userstore = useUserStore();

const emailModalVisible = ref(false);
const confirmLoading = ref(false);
const emailFormRef = ref<FormInstance>();
const countdown = ref(0);
const showVerifyCode = ref(false);
const sendingCode = ref(false);

const emailForm = ref({
  email: '',
  code: ''
});

const emailRules: Record<string, Rule[]> = {
  email: [
    { required: true, message: '请输入邮箱地址' },
    { type: 'email', message: '请输入正确的邮箱格式' }
  ],
  code: [
    { required: true, message: '请输入验证码' },
    { len: 4, message: '验证码长度为4位' }
  ]
};

const showEmailModal = () => {
  emailModalVisible.value = true;
  showVerifyCode.value = false;
  emailForm.value = {
    email: '',
    code: ''
  };
};

const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

const sendVerifyCode = async () => {
  if (sendingCode.value) return;
  
  try {
    await emailFormRef.value?.validateFields(['email']);
    sendingCode.value = true;
    await sendEmailCaptcha(emailForm.value.email);
    message.success('验证码已发送至邮箱');
    startCountdown();
    showVerifyCode.value = true;
    emailForm.value.code = '';
  } catch (error: any) {
    if (error.response?.data?.message) {
      message.error(error.response.data.message);
    } else {
      message.error('发送验证码失败，请重试');
    }
  } finally {
    sendingCode.value = false;
  }
};

const debouncedSendCode = debounce(sendVerifyCode, 500, {
  leading: true,
  trailing: false
});

onBeforeUnmount(() => {
  debouncedSendCode.cancel();
});

const handleEmailBind = async () => {
  if (!showVerifyCode.value) {
    // 校验输入验证码框
    await emailFormRef.value?.validateFields(['code']);
    return;
  }

  try {
    await emailFormRef.value?.validate();
    confirmLoading.value = true;
    
    await bindEmail({
      email: emailForm.value.email,
      emailCode: emailForm.value.code
    });
    
    message.success('邮箱绑定成功');
    emailModalVisible.value = false;
    // 通知父组件刷新数据
    emit('refresh');
  } catch (error: any) {
    if (error.response?.data?.message) {
      message.error(error.response.data.message);
    } else {
      message.error('绑定失败，请重试');
    }
  } finally {
    confirmLoading.value = false;
  }
};

const maskEmail = (email: string) => {
  if (!email) return '';
  
  const [username, domain] = email.split('@');
  if (!username || !domain) return email;
  
  // 用户名部分：保留前3位和最后1位，中间用星号代替
  const maskedUsername = username.length > 4 
    ? `${username.slice(0, 3)}****${username.slice(-1)}`
    : `${username.slice(0, 1)}****${username.slice(-1)}`;
    
  // 域名部分：保留完整显示
  return `${maskedUsername}@${domain}`;
};
</script>

<style lang="scss" scoped>
.settings-container {
  padding: 32px 40px;

  .settings-title {
    font-size: 18px;
    font-weight: 500;
    color: #262626;
    margin-bottom: 24px;
  }

  .settings-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24px;
    background: #fafafa;
    border-radius: 8px;
    margin-bottom: 16px;

    .item-info {
      .item-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 500;
        color: #262626;
        margin-bottom: 8px;
      }

      .item-desc {
        color: #8c8c8c;
        font-size: 14px;
      }
    }
  }
}
</style> 